<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\LessonPublishException;
use App\Models\Attachment;
use App\Models\Lesson;

class LessonController extends Controller
{

    /*
     * @api get /course-api/a/courses/{courseId}/lessons 课时列表
     * @version 0.0.1
     * @group admin
     *
     * @param path int courseId 课程ID
     * @param query int [pageSize] 页数，默认15
     * @param query int [page] 页码，默认1
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *    "total":10,
     *    "items":[]
     * }
     * }
     */
    public function index($courseId)
    {
        $this->request->merge(['courseId' => $courseId]);
        $this->validate($this->request, [
            'courseId' => 'required|integer',
            "pageSize" => "integer|max:100|min:5",
            "page" => "integer|min:1"
        ]);
        $page = intval($this->request->input("page", 1));
        $pageSize = intval($this->request->input("pageSize", 200));
        $query = Lesson::where('course_id', $courseId);
        $total = $query->count();
        $lessons = $query->orderBy('sequence', 'asc')->orderBy('id', 'asc')->forPage($page, $pageSize)
            ->get();
        $items = [];
        if ($total) {
            /** @var Lesson $lesson */
            foreach ($lessons as $lesson) {
                $items[] = [
                    'id' => $lesson->id,
                    'name' => $lesson->getName(),
                    'isPublished' => $lesson->getPublished()
                ];
            }
        }
        return $this->sendSuccessJson(['total'=>$total, 'items'=>$items]);
    }

    /*
     * @api post /course-api/a/courses/{courseId}/lessons 新增课时
     * @version 0.0.1
     * @group admin
     *
     * @param path int courseId 课程ID
     * @param body string name 课时名称
     * @param body string description 课时描述
     * @param body int sequence 课时排序
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function store($courseId)
    {
        $this->request->merge(['courseId' => $courseId]);
        $this->validate($this->request, [
            'courseId' => 'required|integer',
            'name' => 'required|string',
            'description' => 'string',
            'lexile' => 'string'
        ]);
        $name = $this->request->input('name');
        $description = $this->request->input('description', '');
        $lexile = $this->request->input('lexile', '');
        $lessonObj = new Lesson();
        $lessonObj->setCourseId($courseId);
        $lessonObj->setName($name);
        $lessonObj->setDescription($description);
        $lessonObj->setLexile($lexile);
        $lessonObj->setSequence(Lesson::getNextSequence($courseId));
        $lessonObj->save();
        $data = ['id' => $lessonObj->id];
        return $this->sendSuccessJson($data);
    }

    /*
     * @api put /course-api/a/courses/{courseId}/lessons/{lessonId} 更新课时
     * @version 0.0.1
     * @group admin
     *
     * @param path int courseId 课程ID
     * @param path int lessonId 课时ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function update($courseId, $lessonId)
    {
        $this->request->merge(['courseId' => $courseId, 'lessonId' => $lessonId]);
        $this->validate($this->request, [
            'courseId' => 'required|integer',
            'lessonId' => 'required|integer',
            'name' => 'required|string',
            'description' => 'string',
            'lexile' => 'string'
        ]);
        $name = $this->request->input('name');
        $description = $this->request->input('description', '');
        $lexile = $this->request->input('lexile');
        /** @var Lesson $lessonObj */
        $lessonObj = Lesson::find($lessonId);
        $lessonObj->save();
        $lessonObj->setName($name);
        $lessonObj->setDescription($description);
        $lessonObj->setLexile($lexile);
        $lessonObj->save();
        return $this->sendSuccessJson();
    }

    /*
     * @api put /course-api/a/lessons/{lessonId}/introduction 更新课时导读
     * @version 0.0.1
     * @group admin
     *
     * @param path int courseId 课程ID
     * @param path int lessonId 课时ID
     *
     * @param body int attachmentId 附件ID
     * @param body array sentences 介绍
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function updateIntroduction($lessonId)
    {
        $this->request->merge(['id'=>$lessonId]);
        $this->validate($this->request, [
            'id' => 'required|integer',
            'attachmentId' => 'integer',
            'sentences' => 'array'
        ]);
        /** @var Lesson $lessonObj */
        $lessonObj = Lesson::find($lessonId);
        $introduction = $lessonObj->getIntroduction();
        if ($this->request->has('attachmentId')) {
            $introduction['attachmentId'] = $this->request->input('attachmentId');
        }
        if ($this->request->has('sentences')) {
            $introduction['sentences'] = $this->request->input('sentences');
        }
        if ($this->request->has('coverImageId')) {
            $introduction['coverImageId'] = $this->request->input('coverImageId');
        }
        $lessonObj->setIntroduction($introduction);
        $lessonObj->save();
        return $this->sendSuccessJson();
    }

    /*
     * @api get /course-api/a/lessons/{lessonId}/introduction 获取课时导读
     * @version 0.0.1
     * @group admin
     *
     * @param path int courseId 课程ID
     * @param path int lessonId 课时ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function getIntroduction($lessonId)
    {
        $this->request->merge(['id'=>$lessonId]);
        $this->validate($this->request, [
            'id' => 'required|integer',
        ]);
        /** @var Lesson $lessonObj */
        $lessonObj = Lesson::find($lessonId);
        $introduction = $lessonObj->getIntroduction();
        $data = [
            'sentences' => [],
            'attachment' => null
        ];
        if (!empty($introduction['attachmentId'])) {
            $data['attachment'] =  Attachment::where('id', $introduction['attachmentId'])->first(['id', 'name', 'uri', 'ext']);
        }
        if (!empty($introduction['coverImageId'])) {
            $data['cover'] =  Attachment::where('id', $introduction['coverImageId'])->first(['id', 'name', 'uri', 'ext']);
        }
        if (!empty($introduction['sentences'])) {
            foreach ($introduction['sentences'] as $item) {
                $tmp = [
                    'sentence' => $item['sentence'],
                ];
                if (!empty($item['audioId'])) {
                    $tmp['audio'] = Attachment::where('id', $item['audioId'])->first(['id', 'name', 'uri', 'ext']);
                }
                $data['sentences'][] = $tmp;
            }
        }
        return $this->sendSuccessJson($data);
    }

    /*
     * @api put /course-api/a/lessons/{lessonId}/audio 更新课时音频
     * @version 0.0.1
     * @group admin
     *
     * @param path int lessonId 课时ID
     * @param body string audioUrl 音频url
     * @param body int audioId 音频附件ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *    "items":[]
     * }
     * }
     */
    public function audio($lessonId)
    {
        $this->request->merge(['id'=>$lessonId]);
        $this->validate($this->request, [
            'id' => 'required|integer',
            'audioId' => 'integer'
        ]);
        $audioId = $this->request->input('audioId');
        /** @var Lesson $lessonObj */
        $lessonObj = Lesson::find($lessonId);
        $lessonObj->setAudio($audioId);
        $lessonObj->save();
        return $this->sendSuccessJson();
    }


    /*
     * @api put /course-api/a/lessons/{lessonId}/cover 更新课时封面图片
     * @version 0.0.1
     * @group admin
     *
     * @param path int lessonId 知识点ID
     * @param body int imageId 图片附件ID
     * @param body int type 图片类型0原图，1缩略图
     *
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *    "items":[]
     * }
     * }
     */
    public function cover($lessonId)
    {
        $this->request->merge(['id'=>$lessonId]);
        $this->validate($this->request, [
            'id' => 'required|integer',
            'imageId' => 'integer',
            'type' => 'integer'

        ]);
        $image = $this->request->input('imageId');
        $type = $this->request->input('type', 0);
        /** @var Lesson $lessonObj */
        $lessonObj = Lesson::find($lessonId);
        if ($type == 0) {
            $lessonObj->setCover($image);
        } else {
            $lessonObj->setThumbCover($image);
        }
        $lessonObj->save();
        return $this->sendSuccessJson();
    }

    /*
     * @api get /course-api/a/courses/{courseId}/lessons/{lessonId} 课时详情
     * @version 0.0.1
     * @group admin
     *
     * @param path int courseId 课程ID
     * @param path int lessonId 课时ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function show($courseId, $lessonId)
    {
        $this->request->merge(['courseId' => $courseId, 'lessonId' => $lessonId]);
        $this->validate($this->request, [
            'courseId' => 'required|integer',
            'lessonId' => 'required|integer',
        ]);
        /** @var Lesson $lessonObj */
        $lessonObj = Lesson::find($lessonId);
        $data = [
            'id' => $lessonObj->getId(),
            'name' => $lessonObj->getName(),
            'description' => $lessonObj->getDescription(),
            'lexile' => $lessonObj->getLexile(),
            'introduction' => $lessonObj->getIntroduction(),
            'audio' => $lessonObj->audio()->first(['id', 'name', 'uri']),
            'cover' => $lessonObj->cover()->first(['id', 'name', 'uri']),
            'thumbCover' => $lessonObj->thumbCover()->first(['id', 'name', 'uri']),
            'isPublished' => $lessonObj->getPublished()
        ];
        return $this->sendSuccessJson($data);
    }

    /*
     * @api put /course-api/a/courses/{courseId}/lessons-sequence 课时排序
     * @version 0.0.1
     * @group admin
     *
     * @param path int courseId 课程ID
     * @param path array lessonIds 课时ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function sequence($courseId)
    {
        $lessonIds = $this->request->input('lessonIds');
        foreach ($lessonIds as $index => $lessonId) {
            /** @var Lesson $lessonObj */
            $lessonObj = Lesson::find($lessonId);
            $lessonObj->setSequence($index);
            $lessonObj->save();
        }
        return $this->sendSuccessJson();
    }

    /*
     * @api delete /course-api/a/courses/{courseId}/lessons/{lessonId} 删除课时
     * @version 0.0.1
     * @group admin
     *
     * @param path int courseId 课程ID
     * @param path int lessonId 课时ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function destroy($courseId, $lessonId)
    {
        $this->request->merge(['courseId' => $courseId, 'lessonId' => $lessonId]);
        $this->validate($this->request, [
            'courseId' => 'required|integer',
            'lessonId' => 'required|integer',
        ]);
        if (Lesson::where('id', $lessonId)->value('is_published')) {
            throw new LessonPublishException('课时已发布，不能删除');
        }
        Lesson::where('id', $lessonId)->delete();
        return $this->sendSuccessJson();
    }
}
